package com.tgy.leetcode;

import java.util.Arrays;
import java.util.Stack;

/**
 * @Author: tgy
 * @Date: 12/24/20 4:11 PM
 *
 *  https://leetcode-cn.com/problems/candy/
 */
public class _135_分发糖果 {

    public int candy(int[] ratings) {

        if (ratings == null || ratings.length == 0) {

            return 0;
        }

        if (ratings.length == 1) {

            return 1;
        }

        int num = 0;

        int[] nums = new int[ratings.length];
        int[] preMaxIndexs = new int[ratings.length];

        for (int i = 0; i < ratings.length; i++) {

            preMaxIndexs[i] = -1;
        }

        nums[0] = 1;

        //4,1,3,2,2,3,5
        int index = 1;
        while (index < ratings.length) {

            if (ratings[index - 1] < ratings[index]) {

                nums[index] = nums[index - 1] + 1;
            }else if (ratings[index - 1] == ratings[index]) {

                nums[index] = 1;
            }else{

                if (preMaxIndexs[index - 1] < 0) {

                    preMaxIndexs[index] = index - 1;
                }else {

                    preMaxIndexs[index] = preMaxIndexs[index - 1];
                }

                int j = 1;
                nums[index] = j;
                j++;
                for (int i = index - 1; i >= preMaxIndexs[index] ; i--) {

                    if (nums[i] < j) {

                        nums[i] = j;
                    }

                    j++;
                }

            }

            index++;
        }

        System.out.println(Arrays.toString(nums));

        for (int i : nums) {
            num += i;
        }

        return num;
    }
}


